package com.summer.framework.core.filter;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.summer.framework.core.tenant.TenantProperties;
import com.summer.framework.core.tenant.context.TenantContext;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Description: 全局租户信息过滤器
 * @auther Ice Yang
 * Date 2025/7/2 16:54
 */
@Component
@ConditionalOnBean(TenantLineHandler.class)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantFilter implements Filter {

    @Autowired
    private TenantProperties properties;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String tenantId = req.getHeader(properties.getHeaderName());
        try {
            // 设置租户上下文
            TenantContext.setTenantId(tenantId);
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 必须清理，避免内存泄露
            TenantContext.clear();
        }
    }
}
